14.2 コンテキストによる値の伝播
context.WithValueでコンテキストに記載される値には任意の型が使えるが、キーが一意で比較可能であることを保証する必要がある
1. intをベースに独自型を定義する
コンテキストに異なる値を記憶させる場合は、この方法を使用する
code:go
type userKey int // intをベースにしたuserKyeを定義
const (
_ userKey = iota // ゼロ値として定義
key // userKye型の1としてkeyを使用する
)
2. struct{}(空の構造体)を使ってエクスポートされていないキーの型を定義する
キーが一つしか必要ない場合は、どちらの方法でも構わない
code:go
type userKey struct{}
簡単な伝播のコード例
code:go
package main
import (
"context"
"fmt"
)
type userKey struct{}
func main() {
ctx := context.WithValue(context.Background(), userKey{}, "hanako")
doSomething(ctx)
}
func doSomething(ctx context.Context) {
user, ok := ctx.Value(userKey{}).(string)
if ok {
fmt.Println("Hello,", user)
}
}